import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// 一级路由
const Layout = () => import('@/views/layout')
const Login = () => import('@/views/login')
const NotFound = () => import('@/views/404')

// 二级路由
const Home = () => import('@/views/layout/home')
const Qa = () => import('@/views/layout/qa')
const User = () => import('@/views/layout/user')
const Video = () => import('@/views/layout/video')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      { path: '', component: Home },
      { path: '/user', component: User },
      { path: '/qa', component: Qa },
      { path: '/video', component: Video }
    ]
  },
  { path: '/login', component: Login },
  { path: '*', component: NotFound }
]

const router = new VueRouter({
  routes
})

const blackList = ['/user']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token.token
  if (token) {
    next()
  } else {
    if (blackList.includes(to.path)) {
      next('/login')
    } else {
      next()
    }
  }
})

export default router
